<template>
  <a-modal
    v-model:open="visible"
    title="每日签到"
    :footer="null"
    width="900px"
    :closable="true"
    :mask-closable="true"
    class="checkin-modal"
    :destroy-on-close="true"
  >
    <div class="checkin-container">
      <!-- 左侧签到区域 -->
      <div class="checkin-left">
        <div class="checkin-header">
          <div class="header-info">
            <div class="checkin-status">
              <span class="status-text">{{ isCheckedIn ? '您今日已签到' : '今日还未签到' }}</span>
              <span class="points-earned" v-if="isCheckedIn">，获得{{ todayPoints }}积分</span>
            </div>
            <div class="total-points">总积分: {{ totalPoints }}</div>
            <div class="weekly-info">本周已累计签到{{ weeklyCheckins }}天</div>
          </div>
        </div>

        <!-- 每日签到奖励网格 -->
        <div class="daily-rewards-grid">
          <div
            v-for="(day, index) in dailyRewards"
            :key="index"
            class="reward-card"
            :class="{
              completed: day.completed,
              today: day.isToday,
              'double-reward': day.doubleReward,
            }"
          >
            <div class="reward-header">
              <span class="day-title">{{ day.title }}</span>
              <div v-if="day.doubleReward" class="double-badge">双倍奖励</div>
            </div>
            <div class="reward-content">
              <div class="coins-icon">🪙</div>
              <div class="points">{{ day.points }}积分</div>
            </div>
            <div v-if="day.completed" class="completed-icon">✓</div>
          </div>
        </div>

        <!-- 签到规则 -->
        <div class="reward-rule">每周累计签到3天,5天,均可领取双倍奖励,每周一重置签到天数</div>

        <!-- 签到按钮 -->
        <div class="checkin-action">
          <a-button
            type="primary"
            size="large"
            :disabled="isCheckedIn"
            @click="handleCheckin"
            :loading="checkinLoading"
            class="checkin-btn"
          >
            <template #icon>
              <CalendarOutlined />
            </template>
            {{ isCheckedIn ? '今日已签到' : '立即签到' }}
          </a-button>
        </div>
      </div>

      <!-- 右侧功能区 -->
      <div class="checkin-right">
        <!-- 每日任务 -->
        <div class="task-section">
          <div class="section-header">
            <h3 class="section-title">
              <div class="title-bar"></div>
              每日任务
            </h3>
            <a class="more-link">更多任务>></a>
          </div>
          <div class="task-list">
            <div v-for="task in dailyTasks" :key="task.id" class="task-item">
              <div class="task-info">
                <span class="task-name">{{ task.name }}</span>
                <span class="task-points">+{{ task.points }}积分</span>
              </div>
              <a-button
                :type="task.completed ? 'default' : 'primary'"
                size="small"
                :disabled="task.completed"
                @click="handleTask(task)"
                class="task-btn"
              >
                {{ task.completed ? '已完成' : '去完成' }}
              </a-button>
            </div>
          </div>
        </div>

        <!-- 积分兑换 -->
        <div class="exchange-section">
          <div class="section-header">
            <h3 class="section-title">
              <div class="title-bar"></div>
              积分兑换
            </h3>
            <a class="more-link">更多兑换>></a>
          </div>
          <div class="exchange-list">
            <div v-for="item in exchangeItems" :key="item.id" class="exchange-item">
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-price">
                  <span class="original-price">{{ item.originalPrice }}积分</span>
                  <span class="current-price">{{ item.currentPrice }}积分</span>
                </div>
              </div>
              <div class="exchange-action">
                <a-button
                  type="primary"
                  size="small"
                  @click="handleExchange(item)"
                  class="exchange-btn"
                >
                  去兑换
                  <span v-if="item.isNew" class="new-badge">新品上线</span>
                </a-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch } from 'vue'
  import { message } from 'ant-design-vue'
  import { CalendarOutlined } from '@ant-design/icons-vue'
  import { userCheckinUsingPost, getUserCheckinInfoUsingGet } from '@/api/yonghumokuaijiekou'
  import { useLoginUserStore } from '@/stores/useLoginUserStore'

  // Props
  const props = defineProps<{
    open: boolean
  }>()

  // Emits
  const emit = defineEmits<{
    'update:open': [value: boolean]
  }>()

  // 状态管理
  const loginUserStore = useLoginUserStore()

  // 响应式数据
  const visible = ref(false)
  const checkinLoading = ref(false)
  const isCheckedIn = ref(false)
  const totalPoints = ref(5)
  const weeklyCheckins = ref(1)
  const todayPoints = ref(5)

  // 每日签到奖励
  const dailyRewards = ref([
    { title: '第1天', points: 5, completed: true, isToday: false, doubleReward: false },
    { title: '明日', points: 10, completed: false, isToday: true, doubleReward: false },
    { title: '第3天', points: 20, completed: false, isToday: false, doubleReward: true },
    { title: '第4天', points: 10, completed: false, isToday: false, doubleReward: false },
    { title: '第5天', points: 20, completed: false, isToday: false, doubleReward: true },
    { title: '第6天', points: 10, completed: false, isToday: false, doubleReward: false },
    { title: '第7天', points: 10, completed: false, isToday: false, doubleReward: false },
  ])

  // 每日任务
  const dailyTasks = ref([
    {
      id: 1,
      name: '网页签到',
      points: 20,
      completed: true,
      description: '最高+20积分',
    },
    {
      id: 2,
      name: '下载素材',
      points: 10,
      completed: false,
      description: '+10积分',
    },
    {
      id: 3,
      name: '分享网站',
      points: 15,
      completed: false,
      description: '+15积分',
    },
    {
      id: 4,
      name: '上传图片',
      points: 25,
      completed: false,
      description: '+25积分',
    },
  ])

  // 积分兑换
  const exchangeItems = ref([
    {
      id: 1,
      name: '摄图网超绘画VIP日卡',
      originalPrice: 400,
      currentPrice: 24,
      isNew: true,
    },
    {
      id: 2,
      name: '高级素材包',
      originalPrice: 200,
      currentPrice: 150,
      isNew: false,
    },
    {
      id: 3,
      name: 'AI绘画次数',
      originalPrice: 100,
      currentPrice: 80,
      isNew: false,
    },
  ])

  // 监听弹窗状态
  const watchVisible = () => {
    visible.value = props.open
    if (props.open) {
      fetchCheckinInfo()
    }
  }

  // 监听visible变化
  const watchVisibleChange = () => {
    emit('update:open', visible.value)
  }

  // 获取签到信息
  const fetchCheckinInfo = async () => {
    try {
      const res = await getUserCheckinInfoUsingGet()
      if (res.data.code === 200 && res.data.data) {
        const data = res.data.data
        isCheckedIn.value = data.todayChecked || false
        totalPoints.value = data.totalPoints || 5
        weeklyCheckins.value = data.weeklyCheckins || 1
        todayPoints.value = data.todayPoints || 5

        // 更新每日奖励状态
        updateDailyRewards(data.weeklyCheckins || 1)
      }
    } catch (error) {
      console.error('获取签到信息失败:', error)
      // 使用模拟数据
      isCheckedIn.value = false
      totalPoints.value = 5
      weeklyCheckins.value = 1
      todayPoints.value = 5
    }
  }

  // 更新每日奖励状态
  const updateDailyRewards = (checkins: number) => {
    dailyRewards.value.forEach((day, index) => {
      day.completed = index < checkins
      day.isToday = index === checkins
    })
  }

  // 处理签到
  const handleCheckin = async () => {
    if (!loginUserStore.loginUser?.id) {
      message.warning('请先登录')
      return
    }

    checkinLoading.value = true
    try {
      const res = await userCheckinUsingPost()
      if (res.data.code === 200) {
        message.success('签到成功！获得5积分')
        isCheckedIn.value = true
        totalPoints.value += 5
        weeklyCheckins.value += 1
        todayPoints.value = 5

        // 更新每日奖励状态
        updateDailyRewards(weeklyCheckins.value)
      } else {
        message.error(res.data.message || '签到失败')
      }
    } catch (error) {
      console.error('签到失败:', error)
      message.error('签到失败，请稍后重试')

      // 模拟成功
      message.success('签到成功！获得5积分')
      isCheckedIn.value = true
      totalPoints.value += 5
      weeklyCheckins.value += 1
      todayPoints.value = 5
      updateDailyRewards(weeklyCheckins.value)
    } finally {
      checkinLoading.value = false
    }
  }

  // 处理任务
  const handleTask = (task: any) => {
    if (task.completed) return

    // 模拟完成任务
    task.completed = true
    totalPoints.value += task.points
    message.success(`完成任务：${task.name}，获得${task.points}积分`)
  }

  // 处理兑换
  const handleExchange = (item: any) => {
    if (totalPoints.value < item.currentPrice) {
      message.warning('积分不足，无法兑换')
      return
    }

    totalPoints.value -= item.currentPrice
    message.success(`兑换成功：${item.name}`)
  }

  // 生命周期
  onMounted(() => {
    watchVisible()
  })

  // 监听props变化
  watch(() => props.open, watchVisible)
  watch(visible, watchVisibleChange)
</script>

<style scoped>
  .checkin-modal :deep(.ant-modal-content) {
    border-radius: 16px;
    overflow: hidden;
  }

  .checkin-modal :deep(.ant-modal-header) {
    background: linear-gradient(135deg, var(--theme-primary) 0%, var(--theme-secondary) 100%);
    color: var(--theme-surface);
    border-bottom: none;
  }

  .checkin-modal :deep(.ant-modal-title) {
    color: var(--theme-surface);
    font-size: 18px;
    font-weight: 600;
  }

  .checkin-modal :deep(.ant-modal-close) {
    color: var(--theme-surface);
  }

  .checkin-modal :deep(.ant-modal-close:hover) {
    color: var(--theme-textSecondary);
  }

  .checkin-container {
    display: flex;
    gap: 24px;
    min-height: 500px;
  }

  /* 左侧签到区域 */
  .checkin-left {
    flex: 2;
    background: linear-gradient(135deg, var(--theme-surface) 0%, var(--theme-background) 100%);
    border-radius: 16px;
    padding: 24px;
    position: relative;
    overflow: hidden;
  }

  .checkin-left::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 20% 80%, rgba(255, 215, 0, 0.1) 0%, transparent 50%),
      radial-gradient(circle at 80% 20%, rgba(255, 215, 0, 0.1) 0%, transparent 50%);
    pointer-events: none;
  }

  .checkin-header {
    margin-bottom: 24px;
    position: relative;
    z-index: 1;
  }

  .header-info {
    text-align: center;
  }

  .checkin-status {
    font-size: 16px;
    color: var(--theme-text);
    margin-bottom: 8px;
  }

  .status-text {
    font-weight: 600;
  }

  .points-earned {
    color: var(--theme-warning);
    font-weight: 700;
  }

  .total-points {
    font-size: 20px;
    font-weight: 700;
    color: var(--theme-warning);
    margin-bottom: 8px;
  }

  .weekly-info {
    font-size: 14px;
    color: var(--theme-textSecondary);
  }

  /* 每日奖励网格 */
  .daily-rewards-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 12px;
    margin-bottom: 24px;
    position: relative;
    z-index: 1;
  }

  .reward-card {
    background: var(--theme-surface);
    border-radius: 12px;
    padding: 16px 12px;
    text-align: center;
    position: relative;
    transition: all 0.3s ease;
    border: 2px solid var(--theme-border);
  }

  .reward-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px var(--theme-shadow);
  }

  .reward-card.completed {
    background: linear-gradient(135deg, var(--theme-success) 0%, var(--theme-warning) 100%);
    color: var(--theme-surface);
    border-color: var(--theme-success);
  }

  .reward-card.today {
    border-color: var(--theme-primary);
    box-shadow: 0 0 0 2px var(--theme-primary);
  }

  .reward-card.double-reward {
    position: relative;
  }

  .reward-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
  }

  .day-title {
    font-size: 12px;
    font-weight: 600;
    color: inherit;
  }

  .double-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background: var(--theme-error);
    color: var(--theme-surface);
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 8px;
    font-weight: 600;
    transform: rotate(15deg);
  }

  .reward-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
  }

  .coins-icon {
    font-size: 20px;
  }

  .points {
    font-size: 14px;
    font-weight: 700;
    color: inherit;
  }

  .completed-icon {
    position: absolute;
    top: 8px;
    right: 8px;
    background: var(--theme-success);
    color: var(--theme-surface);
    width: 20px;
    height: 20px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 700;
  }

  .reward-rule {
    font-size: 12px;
    color: var(--theme-textSecondary);
    text-align: center;
    margin-bottom: 24px;
    position: relative;
    z-index: 1;
  }

  .checkin-action {
    text-align: center;
    position: relative;
    z-index: 1;
  }

  .checkin-btn {
    height: 48px;
    font-size: 16px;
    font-weight: 600;
    background: linear-gradient(135deg, var(--theme-primary) 0%, var(--theme-secondary) 100%);
    border: none;
    border-radius: 24px;
    color: var(--theme-surface);
    box-shadow: 0 8px 24px var(--theme-shadow);
    transition: all 0.3s ease;
  }

  .checkin-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 32px var(--theme-shadow);
  }

  .checkin-btn:disabled {
    background: #d9d9d9;
    box-shadow: none;
    transform: none;
  }

  /* 右侧功能区 */
  .checkin-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 24px;
  }

  .task-section,
  .exchange-section {
    background: var(--theme-surface);
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 4px 16px var(--theme-shadow);
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 600;
    color: var(--theme-text);
    margin: 0;
  }

  .title-bar {
    width: 4px;
    height: 20px;
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
    border-radius: 2px;
  }

  .more-link {
    font-size: 12px;
    color: var(--theme-primary);
    text-decoration: none;
  }

  .more-link:hover {
    color: var(--theme-secondary);
  }

  /* 任务列表 */
  .task-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .task-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    background: var(--theme-background);
    border-radius: 8px;
    transition: all 0.3s ease;
  }

  .task-item:hover {
    background: var(--theme-surface);
  }

  .task-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .task-name {
    font-size: 14px;
    font-weight: 500;
    color: var(--theme-text);
  }

  .task-points {
    font-size: 12px;
    color: var(--theme-warning);
    font-weight: 600;
  }

  .task-btn {
    height: 32px;
    font-size: 12px;
    border-radius: 16px;
  }

  /* 兑换列表 */
  .exchange-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .exchange-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background: var(--theme-background);
    border-radius: 12px;
    transition: all 0.3s ease;
    position: relative;
  }

  .exchange-item:hover {
    background: var(--theme-surface);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px var(--theme-shadow);
  }

  .item-info {
    flex: 1;
  }

  .item-name {
    font-size: 14px;
    font-weight: 600;
    color: var(--theme-text);
    margin-bottom: 4px;
  }

  .item-price {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .original-price {
    font-size: 12px;
    color: var(--theme-textSecondary);
    text-decoration: line-through;
  }

  .current-price {
    font-size: 14px;
    color: var(--theme-warning);
    font-weight: 700;
  }

  .exchange-action {
    position: relative;
  }

  .exchange-btn {
    height: 32px;
    font-size: 12px;
    border-radius: 16px;
    position: relative;
  }

  .new-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background: var(--theme-error);
    color: var(--theme-surface);
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 8px;
    font-weight: 600;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .checkin-container {
      flex-direction: column;
      gap: 16px;
    }

    .daily-rewards-grid {
      grid-template-columns: repeat(4, 1fr);
      gap: 8px;
    }

    .reward-card {
      padding: 12px 8px;
    }

    .day-title {
      font-size: 10px;
    }

    .points {
      font-size: 12px;
    }

    .coins-icon {
      font-size: 16px;
    }
  }

  @media (max-width: 480px) {
    .daily-rewards-grid {
      grid-template-columns: repeat(3, 1fr);
    }

    .checkin-left {
      padding: 16px;
    }

    .task-section,
    .exchange-section {
      padding: 16px;
    }
  }
</style>
